import { ref, onMounted, onUnmounted } from 'vue'
import { AccessibilityManager, type AccessibilityConfig } from '@/config/accessibility'

// 无障碍访问 Composable
export function useAccessibility() {
  const accessibilityManager = AccessibilityManager.getInstance()
  const config = ref<AccessibilityConfig>(accessibilityManager.getConfig())

  // 更新配置
  const updateConfig = (newConfig: Partial<AccessibilityConfig>) => {
    accessibilityManager.updateConfig(newConfig)
    config.value = accessibilityManager.getConfig()
  }

  // 向屏幕阅读器通知
  const announceToScreenReader = (message: string, priority: 'polite' | 'assertive' = 'polite') => {
    accessibilityManager.announceToScreenReader(message, priority)
  }

  // 配置变化监听器
  const handleConfigChange = (newConfig: AccessibilityConfig) => {
    config.value = newConfig
  }

  onMounted(() => {
    accessibilityManager.addConfigChangeListener(handleConfigChange)
  })

  onUnmounted(() => {
    accessibilityManager.removeConfigChangeListener(handleConfigChange)
  })

  return {
    config,
    updateConfig,
    announceToScreenReader,
  }
}

// 焦点管理 Composable
export function useFocusManagement() {
  const focusHistory = ref<HTMLElement[]>([])
  
  // 保存当前焦点
  const saveFocus = () => {
    const activeElement = document.activeElement as HTMLElement
    if (activeElement && activeElement !== document.body) {
      focusHistory.value.push(activeElement)
    }
  }

  // 恢复焦点
  const restoreFocus = () => {
    const lastFocused = focusHistory.value.pop()
    if (lastFocused && document.contains(lastFocused)) {
      lastFocused.focus()
    }
  }

  // 设置焦点到第一个可聚焦元素
  const focusFirstElement = (container: HTMLElement) => {
    const focusableElements = container.querySelectorAll(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
    )
    
    if (focusableElements.length > 0) {
      (focusableElements[0] as HTMLElement).focus()
    }
  }

  // 创建焦点陷阱
  const createFocusTrap = (container: HTMLElement) => {
    const focusableElements = container.querySelectorAll(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
    )

    if (focusableElements.length === 0) return () => {}

    const firstElement = focusableElements[0] as HTMLElement
    const lastElement = focusableElements[focusableElements.length - 1] as HTMLElement

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Tab') {
        if (event.shiftKey) {
          if (document.activeElement === firstElement) {
            event.preventDefault()
            lastElement.focus()
          }
        } else {
          if (document.activeElement === lastElement) {
            event.preventDefault()
            firstElement.focus()
          }
        }
      }
    }

    container.addEventListener('keydown', handleKeyDown)
    firstElement.focus()

    return () => {
      container.removeEventListener('keydown', handleKeyDown)
    }
  }

  return {
    focusHistory,
    saveFocus,
    restoreFocus,
    focusFirstElement,
    createFocusTrap,
  }
}

// 键盘导航 Composable
export function useKeyboardNavigation() {
  const keyboardListeners = ref<Map<string, (event: KeyboardEvent) => void>>(new Map())

  // 添加键盘快捷键
  const addShortcut = (key: string, callback: (event: KeyboardEvent) => void) => {
    keyboardListeners.value.set(key, callback)
  }

  // 移除键盘快捷键
  const removeShortcut = (key: string) => {
    keyboardListeners.value.delete(key)
  }

  // 处理键盘事件
  const handleKeyDown = (event: KeyboardEvent) => {
    const key = event.key.toLowerCase()
    const modifiers = []
    
    if (event.ctrlKey) modifiers.push('ctrl')
    if (event.altKey) modifiers.push('alt')
    if (event.shiftKey) modifiers.push('shift')
    if (event.metaKey) modifiers.push('meta')

    const shortcutKey = modifiers.length > 0 ? `${modifiers.join('+')}+${key}` : key
    const callback = keyboardListeners.value.get(shortcutKey)
    
    if (callback) {
      event.preventDefault()
      callback(event)
    }
  }

  onMounted(() => {
    document.addEventListener('keydown', handleKeyDown)
  })

  onUnmounted(() => {
    document.removeEventListener('keydown', handleKeyDown)
  })

  return {
    addShortcut,
    removeShortcut,
  }
}

// 屏幕阅读器 Composable
export function useScreenReader() {
  const announcements = ref<string[]>([])

  // 创建实时区域
  const createLiveRegion = (id: string, level: 'polite' | 'assertive' = 'polite') => {
    let region = document.getElementById(id)
    
    if (!region) {
      region = document.createElement('div')
      region.id = id
      region.setAttribute('aria-live', level)
      region.setAttribute('aria-atomic', 'true')
      region.style.cssText = `
        position: absolute;
        left: -10000px;
        width: 1px;
        height: 1px;
        overflow: hidden;
      `
      document.body.appendChild(region)
    }
    
    return region
  }

  // 向屏幕阅读器通知
  const announce = (message: string, level: 'polite' | 'assertive' = 'polite') => {
    const regionId = level === 'assertive' ? 'sr-status' : 'sr-messages'
    const region = createLiveRegion(regionId, level)
    
    region.textContent = message
    announcements.value.push(message)
    
    // 清除消息
    setTimeout(() => {
      region.textContent = ''
    }, 1000)
  }

  // 通知页面变化
  const announcePageChange = (pageName: string) => {
    announce(`已导航到 ${pageName} 页面`, 'assertive')
  }

  // 通知加载状态
  const announceLoading = (isLoading: boolean, message?: string) => {
    if (isLoading) {
      announce(message || '正在加载...', 'polite')
    } else {
      announce('加载完成', 'polite')
    }
  }

  // 通知错误
  const announceError = (error: string) => {
    announce(`错误：${error}`, 'assertive')
  }

  // 通知成功
  const announceSuccess = (message: string) => {
    announce(`成功：${message}`, 'polite')
  }

  return {
    announcements,
    announce,
    announcePageChange,
    announceLoading,
    announceError,
    announceSuccess,
  }
}

// ARIA 属性管理 Composable
export function useAriaAttributes() {
  // 设置 ARIA 标签
  const setAriaLabel = (element: HTMLElement, label: string) => {
    element.setAttribute('aria-label', label)
  }

  // 设置 ARIA 描述
  const setAriaDescription = (element: HTMLElement, description: string) => {
    const descId = `desc-${Date.now()}`
    
    let descElement = document.getElementById(descId)
    if (!descElement) {
      descElement = document.createElement('div')
      descElement.id = descId
      descElement.style.cssText = `
        position: absolute;
        left: -10000px;
        width: 1px;
        height: 1px;
        overflow: hidden;
      `
      descElement.textContent = description
      document.body.appendChild(descElement)
    }
    
    element.setAttribute('aria-describedby', descId)
  }

  // 设置 ARIA 展开状态
  const setAriaExpanded = (element: HTMLElement, expanded: boolean) => {
    element.setAttribute('aria-expanded', expanded.toString())
  }

  // 设置 ARIA 选中状态
  const setAriaSelected = (element: HTMLElement, selected: boolean) => {
    element.setAttribute('aria-selected', selected.toString())
  }

  // 设置 ARIA 禁用状态
  const setAriaDisabled = (element: HTMLElement, disabled: boolean) => {
    element.setAttribute('aria-disabled', disabled.toString())
  }

  // 设置 ARIA 隐藏状态
  const setAriaHidden = (element: HTMLElement, hidden: boolean) => {
    element.setAttribute('aria-hidden', hidden.toString())
  }

  // 设置 ARIA 当前状态
  const setAriaCurrent = (element: HTMLElement, current: string | boolean) => {
    element.setAttribute('aria-current', current.toString())
  }

  return {
    setAriaLabel,
    setAriaDescription,
    setAriaExpanded,
    setAriaSelected,
    setAriaDisabled,
    setAriaHidden,
    setAriaCurrent,
  }
}

// 颜色对比度检查 Composable
export function useColorContrast() {
  // 计算相对亮度
  const getRelativeLuminance = (color: string): number => {
    const rgb = hexToRgb(color)
    if (!rgb) return 0

    const [r, g, b] = [rgb.r, rgb.g, rgb.b].map(c => {
      c = c / 255
      return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4)
    })

    return 0.2126 * r + 0.7152 * g + 0.0722 * b
  }

  // 十六进制转RGB
  const hexToRgb = (hex: string): { r: number; g: number; b: number } | null => {
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
    return result ? {
      r: parseInt(result[1], 16),
      g: parseInt(result[2], 16),
      b: parseInt(result[3], 16)
    } : null
  }

  // 计算对比度
  const getContrastRatio = (color1: string, color2: string): number => {
    const l1 = getRelativeLuminance(color1)
    const l2 = getRelativeLuminance(color2)
    const lighter = Math.max(l1, l2)
    const darker = Math.min(l1, l2)
    
    return (lighter + 0.05) / (darker + 0.05)
  }

  // 检查对比度是否符合 WCAG 标准
  const checkWCAGCompliance = (
    foreground: string, 
    background: string, 
    level: 'AA' | 'AAA' = 'AA',
    size: 'normal' | 'large' = 'normal'
  ): boolean => {
    const ratio = getContrastRatio(foreground, background)
    
    if (level === 'AAA') {
      return size === 'large' ? ratio >= 4.5 : ratio >= 7
    } else {
      return size === 'large' ? ratio >= 3 : ratio >= 4.5
    }
  }

  // 获取建议的颜色
  const getSuggestedColor = (
    baseColor: string, 
    backgroundColor: string, 
    targetRatio = 4.5
  ): string => {
    // 这里可以实现颜色调整算法
    // 简化实现，返回基础颜色
    return baseColor
  }

  return {
    getContrastRatio,
    checkWCAGCompliance,
    getSuggestedColor,
  }
}